/**
 * @desc
 *
 * 从源码文件中提取矢量
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/11/28
 **/
'use strict';

var svgRepoUtil  =require('../loaders/svg-repo-util');

var ConcatSource = require("webpack-core/lib/ConcatSource");

function MyPlugin() {}

MyPlugin.prototype.apply = function(compiler) {
  console.log('svg  plugin 开始发挥其作用了. !!');
  compiler.plugin('emit', function(compilation, callback) {
    
    // Explore each chunk (build output):
    // compilation.chunks.forEach(function(chunk) {
    //   // Explore each module within the chunk (built inputs):
    //   chunk.modules.forEach(function(module) {
    //     // Explore each source file path that was included into the module:
    //     (module.fileDependencies || []).forEach(function(filepath) {
    //        console.log('filepath:',filepath);
    //       // we've learned a lot about the source structure now...
    //     });
    //   });
    //
    //   // Explore each asset filename generated by the chunk:
    //   chunk.files.forEach(function(filename) {
    //     console.log('filename:',filename);
    //     // Get the asset source for each file generated by the chunk:
    //     var source = compilation.assets[filename].source();
    //   });
    // });
    
    callback();
  });
  
  
  compiler.plugin("compilation", function(compilation) {
    compilation.plugin("optimize-chunk-assets", function(chunks, callback) {
      
      let _svgArrayMaps ={};
      // Explore each chunk (build output):
      chunks.forEach(function(chunk,_chunkIndex) {
        
        // Explore each asset filename generated by the chunk:
        // chunk.files.forEach(function(filename) {
        //   // console.log('filename:',filename);
        //   // Get the asset source for each file generated by the chunk:
        //   // var source = compilation.assets[filename].source();
        // });
    
        // Explore each module within the chunk (built inputs):
        chunk.modules.forEach(function(module) {
          // Explore each source file path that was included into the module:
          (module.fileDependencies || []).forEach(function(filepath) {
            if(svgRepoUtil.getSvgsByFilePath(filepath).length>0){
              console.log('获取的SVG信息为::',svgRepoUtil.getSvgsByFilePath(filepath));
  
              if(!_svgArrayMaps[_chunkIndex]){
                _svgArrayMaps[_chunkIndex] = [];
              }
              _svgArrayMaps[_chunkIndex]  = _svgArrayMaps[_chunkIndex].concat(svgRepoUtil.getSvgsByFilePath(filepath));
            }
            // we've learned a lot about the source structure now...
          });
        });
    
      });
      
      for(let chunkIndex  in _svgArrayMaps){
        console.log(_svgArrayMaps[chunkIndex]);
        chunks[chunkIndex].files.forEach(function(file) {
          if(file.endsWith('.js')){
            compilation.assets[file] = new ConcatSource(insertSvgInfo({
              buidSource:compilation.assets[file].source(),
              svgs:_svgArrayMaps[chunkIndex]})
            );
          }
          // compilation.assets[file] = new ConcatSource("\/**Sweet Banner**\/", "\n", compilation.assets[file]);
        });
      }
      callback();
    });
  });
  
};


/**
 *
 * @param buidSource
 * @param svgs
 */
function  insertSvgInfo ({buidSource,svgs}){
  let _begIndex =  buidSource.indexOf('__XSite_widgetInject');
  if (_begIndex === -1  && buidSource.indexOf('module.exports') >= 0) {
    throw new Error("组件中没有包含__XSite_widgetInject，请把组件中的module.exports改为__XSite_widgetInject");
  }
  let _insertIndex  = buidSource.indexOf('{',_begIndex) +1;
  
  let  content0  =buidSource.substring(0,_insertIndex) ,content1  =buidSource.substring(_insertIndex);
  return  `${content0} "svgs":${JSON.stringify(svgs)}, ${content1}`;
}


module.exports = MyPlugin;